package model

import (
	"fmt"
	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
	"log"
	"math/rand"
	"myGame/src/Config"
	"time"
)

// 一个用于后续使用随机数的两个方法
var randSeed = rand.NewSource(time.Now().UnixNano())
var randGen = rand.New(randSeed)

type Obstacle struct {
	Image        []*ebiten.Image
	Width        []float64
	Height       []float64
	X            []float64
	Y            []float64
	ObstacleType []int
}

func ObstacleInit() *Obstacle {
	img1, _, err := ebitenutil.NewImageFromFile("./src/images/dimian.png")
	if err != nil {
		log.Fatal(err)
	}
	img2, _, err := ebitenutil.NewImageFromFile("./src/images/kongzhong.png")
	if err != nil {
		log.Fatal(err)
	}
	width1, height1 := img1.Size()
	width2, height2 := img2.Size()
	//fmt.Println(width1, height1)240 258
	//fmt.Println(width2, height2)	240 420
	obs := &Obstacle{
		Image:        []*ebiten.Image{img1, img2},
		Width:        []float64{float64(width1), float64(width2)},
		Height:       []float64{float64(height1), float64(height2)},
		X:            []float64{550, 1100},
		Y:            []float64{500, 120}, //315
		ObstacleType: []int{0, 1},
	}
	return obs
}
func (Obstacle *Obstacle) Draw(screen *ebiten.Image, cfg *Config.Config) {
	op1 := &ebiten.DrawImageOptions{}
	//index为0的障碍物
	op1.GeoM.Translate(Obstacle.X[0], Obstacle.Y[0])
	Obstacle.X[0] -= cfg.ObstacleSpeed
	//如果障碍物完全离开屏幕，则重新生成障碍物
	if Obstacle.X[0]+Obstacle.Width[1] <= 0 {
		Obstacle.X[0] = float64(randGen.Intn(600)) + 900 //1		280--1680
		juddis(&Obstacle.X[0], &Obstacle.X[1])
	}

	//index为1的障碍物
	op2 := &ebiten.DrawImageOptions{}
	op2.GeoM.Translate(Obstacle.X[1], Obstacle.Y[1])
	Obstacle.X[1] -= cfg.ObstacleSpeed
	//如果障碍物完全离开屏幕，则重新生成障碍物
	if Obstacle.X[1]+Obstacle.Width[1] <= 0 {
		Obstacle.X[1] = float64(randGen.Intn(600)) + 900 //1280---2080
		juddis(&Obstacle.X[1], &Obstacle.X[0])
	}
	screen.DrawImage(Obstacle.Image[0], op1)
	screen.DrawImage(Obstacle.Image[1], op2)

}

// 写一个判断方法，如果新生成的障碍物和另外一个障碍物的距离过近的话，就让他改变位置
func juddis(a *float64, b *float64) {
	if *a >= *b {
		if *a-*b < 400 {
			*a = 560 + *b
			fmt.Printf("1")
		}
	} else {
		//主要是新创建的又概率是在上一个创建的前面，
		//如果是这样的话，就要进行接下来的操作。
		if *b-*a < 400 {
			*b = 600 + *a
			fmt.Printf("2")
		}
	}
}
